package com.tuyan.aixiang.common;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.activity.web.WebActivity;
import com.tuyan.aixiang.common.lang.VoidFunction;
import com.tuyan.aixiang.component.LoadingDialog;
import com.tuyan.aixiang.util.ToastUtil;
//import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
//import pub.devrel.easypermissions.AfterPermissionGranted;
//import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IView {

    private static final String TAG = "BaseActivity";

    protected P iPresenter;

    protected Unbinder unbinder;

    LoadingDialog loadingDialog;

    CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        // lock portrait screen orientation
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        bindView();
    }


    @Override
    protected void onPostResume() {
        super.onPostResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        hideLoading();
        unBindView();
    }

    @Override
    public void addDisposable(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    @Override
    public void bindView() {
        unbinder = ButterKnife.bind(this);
        iPresenter = createPresenter();
        if (null != iPresenter) {
            iPresenter.register(this);
        }
        loadingDialog = new LoadingDialog(this);
    }

    @Override
    public void unBindView() {
        if (null != unbinder) {
            unbinder.unbind();
        }
        if (null != iPresenter) {
            iPresenter.unRegister();
        }
    }

    @Override
    public void showLoading(String text, boolean block) {
        loadingDialog.setLoadingText(text).setInterceptBack(block).show();
    }

    @Override
    public void showLoading(boolean block) {
        showLoading("加载中", block);
    }

    @Override
    public void hideLoading() {
        loadingDialog.close();
    }

    @Override
    public void showLoading() {
        showLoading(false);
    }

    @Override
    public String getFormText(AppCompatEditText et) {
        return et.getText().toString().trim();
    }


    @Override
    public void addDefaultBack() {
//        LinearLayout mback = findViewById(R.id.ll_back);
//        mback.setOnClickListener(v -> finish());
    }

    @Override
    public void immersion() {
        ImmersionBar.with(this).flymeOSStatusBarFontColor(R.color.textDark).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    public void fitSystemWindow(int color) {
        ImmersionBar.with(this).keyboardEnable(true)  //解决软键盘与底部输入框冲突问题
//                .flymeOSStatusBarFontColor(R.color.textDark)
                .statusBarDarkFont(true, 0.2f)
                .fitsSystemWindows(true)
                .statusBarColor(color)
                .init();
    }
    @Override
    public void openWeb(String link) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra("url", link);
        startActivity(intent);
    }


    @Override
    public void fullScreen() {
        ImmersionBar.with(this).fullScreen(true).init();

    }

    protected abstract int getLayoutId();

    protected abstract P createPresenter();

    @Override
    public void loadImage(String uuid, ImageView iv) {
        if (null == uuid || null == iv) return;
        iPresenter.loadImage(uuid, url -> {
            if (null == url) return;
            Glide.with(this).load(url).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv);
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }



    @Override
    public void withLocationPermission(VoidFunction func) {
//        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
//        if (EasyPermissions.hasPermissions(this, perms)) {
//            func.call();
//        } else {
//            EasyPermissions.requestPermissions(this, "请求定位权限以提供定位功能", 8883, perms);
//        }
        withPermission(new String[]{Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION}, "请打开定位权限", () -> {
            func.call();
        }, () ->{});
    }

    @Override
    public void withRecordPermission(VoidFunction func) {
//        String[] perms = {Manifest.permission.RECORD_AUDIO, Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        withPermission(new String[]{Permission.RECORD_AUDIO,
        Permission.WRITE_EXTERNAL_STORAGE}, "请打开录音和存储权限", () -> {
            func.call();
        }, () ->{});
    }

    @Override
    public void withCameraPermission(VoidFunction func) {
        withPermission(new String[]{
                Permission.CAMERA}, "请打开相机权限", () -> {
            func.call();
        }, () ->{});
    }

    public void withPermission(String[] permissions, String hint, Action granted, Action denied) {
        XXPermissions.with(this)
                .permission(permissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            granted.call();
                        } else {
                            denied.call();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtil.makeShort(hint);
                            XXPermissions.startPermissionActivity(BaseActivity.this, permissions);
                        } else {
                            ToastUtil.makeShort("获取权限失败");
                        }
                        denied.call();
                    }
                });
    }



}
